﻿using Elasticsearch.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nest;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZYHand.Entity;
using ZYHand.IRepository;

namespace ZYHand.Repository
{
    public class RabbitMQRepository: IRabbitMQRepository
    {
        public RabbitMQRepository()
        {
        }
        public bool Publish(string queue, string exchange, string routingkey, byte[] buffer)
        {
            try
            {
                using (var connection = RabbitMQClient.GetInstance().CreateConnection())//连接服务器，即正在创建终结点。
                {
                    //创建一个通道，这个就是Rabbit自己定义的规则了，如果自己写消息队列，这个就可以开脑洞设计了
                    //这里Rabbit的玩法就是一个通道channel下包含多个队列Queue
                    using (var channel = connection.CreateModel())
                    {
                        channel.ExchangeDeclare(exchange, ExchangeType.Direct, true);//交换机，true持久化
                        channel.QueueDeclare(queue, true, false, false, null);//创建一个名称为""的消息队列，true持久化
                        channel.QueueBind(queue, exchange, routingkey, null);//绑定队列到指定交换机上

                        var properties = channel.CreateBasicProperties();
                        properties.DeliveryMode = 2;  //1非持久化，2持久化

                        channel.BasicPublish(exchange, routingkey, properties, buffer); //生产消息，把数据推入MQ中

                        //返回给客户端信息
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
